package com.zsx.shopping.auth.service.impl;

import com.zsx.shopping.auth.constant.AuthConstant;
import com.zsx.shopping.auth.enums.AuthCodeMsg;
import com.zsx.shopping.auth.service.VerifyService;
import com.zsx.shopping.auth.utils.VerifyCodeUtils;
import com.zsx.shopping.common.exception.ShoppingException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Service
public class VerifyServiceImpl implements VerifyService {

    @Resource
    private HttpServletRequest request;

    @Override
    public void setVerifyCode(Integer width, Integer height, HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        HttpSession session = request.getSession();
        String code = VerifyCodeUtils.generateVerifyCode(4);
        session.setAttribute(AuthConstant.VERIFY_CODE, code);
        try {
            VerifyCodeUtils.outputImage(width, height, response.getOutputStream(), code);
        } catch (IOException ignored) {

        }
    }

    @Override
    public void checkVerifyCode(String code) {
        HttpSession session = request.getSession();
        String code_session = (String) session.getAttribute(AuthConstant.VERIFY_CODE);
        session.removeAttribute(AuthConstant.VERIFY_CODE);
        if (code_session == null) {
            AuthCodeMsg codeMsg = AuthCodeMsg.VERIFY_CODE_INVALID;
            throw new ShoppingException(codeMsg.getCode(), codeMsg.getMsg());
        } else if (!code_session.equalsIgnoreCase(code)) {
            AuthCodeMsg codeMsg = AuthCodeMsg.VERIFY_CODE_WRONG;
            throw new ShoppingException(codeMsg.getCode(), codeMsg.getMsg());
        }
    }
}
